//
//  RVSearchViewController.m
//  RememberVocabularies
//
//  Created by 伍银荣 on 2017/10/14.
//  Copyright © 2017年 WYR. All rights reserved.
//

#import "RVSearchViewController.h"
#import <sqlite3.h>
#import "RVTableViewController.h"

@interface RVSearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UISearchBar *searBar;
@property (nonatomic,strong) UITableView *myTableView;
//显示搜索的单词数组
@property (nonatomic,strong) NSMutableArray *displayMarr;

//总的单词数组
@property (nonatomic,strong) NSArray *wordsArr;

@end

@implementation RVSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self readSqlitFile];
    
    [self setupUI];
}

-(void)setupUI
{
    self.navigationItem.titleView = self.searBar;
    [self.view addSubview:self.myTableView];
}

-(UISearchBar *)searBar
{
    if (!_searBar) {
        UISearchBar *searBar = [[UISearchBar alloc]init];
        searBar.placeholder = @"请输入要查询的单词";
        searBar.showsCancelButton = YES;
        searBar.delegate = self;
        _searBar = searBar;
    }
    return _searBar;
}
-(NSArray *)wordsArr
{
    if (!_wordsArr) {
        _wordsArr = [NSArray array];
}
    return _wordsArr;
}

-(NSMutableArray *)displayMarr
{
    if (!_displayMarr) {
        _displayMarr = [NSMutableArray array];
    }
    return _displayMarr;
}

-(UITableView *)myTableView
{
    if (!_myTableView) {
        UITableView *myTableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
        myTableView.delegate = self;
        myTableView.dataSource = self;
        myTableView.tableFooterView = [UIView new];
        _myTableView = myTableView;
    }
    return _myTableView;
}

#pragma mark - <UITableViewDataSource>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.displayMarr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

#pragma mark - <UITabelViewDelegate>

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"myCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    cell.textLabel.text = self.displayMarr[indexPath.row][@"en"];
    cell.detailTextLabel.text = self.displayMarr[indexPath.row][@"zh"];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RVTableViewController *tableVC = [[RVTableViewController alloc]init];
    tableVC.english = self.displayMarr[indexPath.row][@"en"];
    tableVC.navigationItem.title = @"单词释义";
    [self.navigationController pushViewController:tableVC animated:YES];
}



#pragma mark - <UISearchBarDelegate>
//返回按钮的代理
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"searchText:%@",searchText);
    //拿到输入的内容，searchText到_wordsArr寻找
    if (searchText.length > 0) {
        [self.displayMarr removeAllObjects];
        for (NSDictionary *dict in self.wordsArr) {
            NSRange textRange = [dict[@"en"] rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if (textRange.length > 0) {
                [self.displayMarr addObject:dict];
            }
        }
    } else {
        [self.displayMarr removeAllObjects];
    }
    [self.myTableView reloadData];
    
}



//界面即将出现(弹出键盘)
-(void)viewWillAppear:(BOOL)animated
{
   [super viewWillAppear:animated];
    [self.searBar becomeFirstResponder];
}

//界面即将消失（收回键盘）
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.searBar resignFirstResponder];
    
}


-(void) readSqlitFile
{
    //获取db path
    NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"words.db" ofType:nil];
    //创建db
    sqlite3 *db;
    //判断是否能够打开db
    if (sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK) {
        NSLog(@"sqlite dadabase is opened.");
    } else {
        NSLog(@"sqlite dadabase open fail.");
    }
    
    sqlite3_stmt *statement;
    NSMutableArray *wordsArr = [[NSMutableArray alloc]init];
    // @"select * from words"  查询所有 key 值内容
    NSString *selectSql = @"select id, en TEXT, zh TEXT from words";
    if (sqlite3_prepare(db, [selectSql UTF8String], -1, &statement, nil) == SQLITE_OK) {
        //遍历db-table每一行
        while (sqlite3_step(statement) == SQLITE_ROW) {
            // 查询 id 的值
            int _id = sqlite3_column_int(statement, 0);
            // 查询 en 的值
            NSString *en = [[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
            // 查询 zh 的值
            NSString *zh = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)];
            
            NSDictionary *dict = @{@"_id":[NSString stringWithFormat:@"%d",_id], @"en":en, @"zh":zh};
            [wordsArr addObject:dict];
        }
        _wordsArr = wordsArr;
        NSLog(@"------wordsArr:%@",_wordsArr);
        
    } else {
        NSLog(@"error");
    }
}


@end
